Skip to content

Fix shapeless unflatten shape inference - #4981

Merged
zcbenz merged 1 commit into
ml-explore:mainfrom
Waterpine:fix/shapeless-unflatten-inference
Nov 28, 2026
Merged

zcbenz merged 1 commit into
ml-explore:mainfrom
Waterpine:fix/shapeless-unflatten-inference

Conversation

@Waterpine

Copy link
Copy Markdown
Contributor

Fix mx.unflatten shape inference when reusing a function compiled with shapeless=True.

Previously, -1 was resolved during tracing and stored as a fixed dimension. Later calls with different input sizes reused that dimension, producing incorrect output shapes.

This change preserves -1 in the primitive and infers it from each input. It also validates shape compatibility on subsequent calls and retains validation for fixed single-dimension shapes.

import mlx.core as mx

f = mx.compile(
    lambda x: mx.unflatten(x, 0, (2, -1)),
    shapeless=True,
)

for n in (8, 12, 4, 0, 3):
    try:
        print(n, f(mx.arange(n)).shape)
    except ValueError:
        print(n, "ValueError")

Before:

8 (2, 4)
12 (2, 4)
4 (2, 4)
0 (2, 4)
3 (2, 4)

After:

8 (2, 4)
12 (2, 6)
4 (2, 2)
0 (2, 0)
3 ValueError

Adds regression coverage for changing input sizes, empty inputs, invalid shapes, non-contiguous inputs, function transforms, and shapeless export/import.

@zcbenz
zcbenz force-pushed the fix/shapeless-unflatten-inference branch from 350f97e to 6694b77 Compare November 28, 2026 00:49
@zcbenz
zcbenz merged commit 38fd510 into ml-explore:main Nov 28, 2026
24 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants